package com.niodata.dp.plugin.spring;

import com.niodata.dp.plugin.core.AbstractDpTaskPlugin;
import java.io.InputStream;
import java.util.Properties;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

public class DpTaskSpringRunner {

  private static Class<AbstractDpTaskPlugin> pluginClazz;
  private static boolean mybatisEnabled = false;

  public static void main(String[] args) throws Exception {
      new DpTaskSpringRunner().execute();
  }

  public void  execute() throws Exception {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
    Resource resource = new DefaultResourceLoader().getResource("classpath:/components.properties");
    Properties props = new Properties();
    if (resource == null) {
      throw new RuntimeException("components.properties not found");
    }
    InputStream inputStream = resource.getInputStream();
    props.load(inputStream);
    inputStream.close();
    mybatisEnabled = Boolean.valueOf(props.getProperty("mybatisEnabled", "false"));
    String pluginClass = props.getProperty("pluginClass");
    pluginClazz = (Class<AbstractDpTaskPlugin>)Class.forName(pluginClass);
    String basePkgs = props.getProperty("basePackages");
    String[] pkgs = new String[0];
    if (basePkgs != null && basePkgs.length() > 0) {
      pkgs = basePkgs.split(";");
    }
    if (mybatisEnabled) {
      String[] pkgs1 = new String[pkgs.length + 1];
      System.arraycopy(pkgs,  0, pkgs1, 0, pkgs.length);
      pkgs1[pkgs.length] = "com.niodata.dp.plugin.spring";
      pkgs = pkgs1;
    }
    String beans = props.getProperty("beans");
    String[] beanArray = beans.split(";");
    if (beans != null && beans.length() > 0) {
      for (String bean : beanArray) {
        context.register(Class.forName(bean));
      }
    }
    context.scan(pkgs);
    context.refresh();
    AbstractDpTaskPlugin plugin = (AbstractDpTaskPlugin)context.getBean(pluginClazz);
    plugin.execute();
  }

}
